package com.infomanage.service.rule;

import java.io.File;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;

import com.infomanage.authority.AuthorityBean;
import com.infomanage.bean.FieldBean;
import com.infomanage.bean.PaginationBean;
import com.infomanage.bean.SearchBean;
import com.infomanage.dao.EmergencyAccidentSummaryDAO;
import com.infomanage.dao.EmergencyTrafficPicDAO;
import com.infomanage.dao.RuleMeetingDAO;
import com.infomanage.enums.RoleType;
import com.infomanage.po.EmergencyAccidentSummary;
import com.infomanage.po.EmergencyTrafficPic;
import com.infomanage.po.RuleMeeting;
import com.infomanage.po.User;
import com.infomanage.util.Consts;
import com.infomanage.util.FileUpload;
import com.infomanage.util.StringUtil;
import com.infomanage.util.TimeUtil;
import com.infomanage.util.smartupload.SmartRequest;
import com.infomanage.util.smartupload.SmartUpload;
import com.jiuqi.util.ReturnObject;
import com.jiuqi.util.StringUtils;

public class RuleMeetingService {

	public static RuleMeeting loadRuleMeeting(HttpServletRequest request, HttpServletResponse response, JspWriter out){
		try {
			request.setCharacterEncoding("UTF-8");
			String picId= request.getParameter("itemId");
			if(StringUtils.isEmpty(picId)) return null;
			RuleMeetingDAO dao = new RuleMeetingDAO();
			return dao.find(RuleMeeting.class, Integer.parseInt(picId));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static List<RuleMeeting> loadRuleMeetingList(HttpServletRequest request, HttpServletResponse response, JspWriter out){
		try {
			request.setCharacterEncoding("UTF-8");
			RuleMeetingDAO dao = new RuleMeetingDAO();
			List<RuleMeeting> list = dao.findAll(RuleMeeting.class);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private static ReturnObject saveRuleMeeting(
			SmartUpload smartUpload, User user) {
		SmartRequest request = smartUpload.getRequest();
		String[] fileNames = smartUpload.getFileNames();
		ReturnObject ret = new ReturnObject();
		try {
			RuleMeeting pic = new RuleMeeting();
			RuleMeetingDAO dao = new RuleMeetingDAO();
			String picName = request.getParameter("name");
			pic.setName(picName);
			if(fileNames != null && fileNames.length > 0){
				String dir = fileNames[0].substring(fileNames[0].lastIndexOf("\\") + 1);
				pic.setFileDir(dir);
			}
			pic.setTimestamp(TimeUtil.showCurrentDay());
			if(user != null){
				pic.setUserName(user.getUserName());
				if(user.getRoleId() == RoleType.SYSADMIN.value() || user.getRoleId() == RoleType.DDADMIN.value()){
					pic.setDeptId(1);
				}else{
					pic.setDeptId(user.getAssociatedDept());
				}
			}
			pic.setDescription(request.getParameter("description"));
			dao.add(pic);
		} catch (Exception e) {
			e.printStackTrace();
			ret.SetErrored(true);
			ret.setErrorMessage(StringUtil.filterIllegalchar(e.getMessage()));
		
		}
		return ret;
	}
	public static ReturnObject modifyRuleMeeting(
			SmartUpload smartUpload, User user){
		SmartRequest request = smartUpload.getRequest();
		String itemId = request.getParameter("itemId");
		String[] fileNames = smartUpload.getFileNames();
		ReturnObject ret = new ReturnObject();
		try {
			RuleMeetingDAO dao = new RuleMeetingDAO();
			RuleMeeting pic = dao.find(RuleMeeting.class, Integer.parseInt(itemId));
			if(fileNames != null && fileNames.length > 0){
				String dir = fileNames[0].substring(fileNames[0].lastIndexOf("\\") + 1);
				pic.setFileDir(dir);
			}
			pic.setTimestamp(TimeUtil.showCurrentDay());
			if(user != null){
				pic.setUserName(user.getUserName());
				if(user.getRoleId() == RoleType.SYSADMIN.value() || user.getRoleId() == RoleType.DDADMIN.value()){
					pic.setDeptId(1);
				}else{
					pic.setDeptId(user.getAssociatedDept());
				}
			}
			dao.modify(pic);
		} catch (Exception e) {
			e.printStackTrace();
			ret.SetErrored(true);
			ret.setErrorMessage(StringUtil.filterIllegalchar(e.getMessage()));
		
		}
		return ret;
	}
	
	public static ReturnObject modifyRuleMeeting(HttpServletRequest request, HttpServletResponse response, JspWriter out){
		ReturnObject ret = new ReturnObject();
		try {
			request.setCharacterEncoding("UTF-8");
			int itemId = Integer.parseInt(request.getParameter("itemId"));
			RuleMeetingDAO dao = new RuleMeetingDAO();
			RuleMeeting bean = dao.find(RuleMeeting.class, itemId);
			bean.setDescription(request.getParameter("description"));
			bean.setName(request.getParameter("name"));
			dao.modify(bean);
		} catch (Exception e) {
			ret.SetErrored(true);
			ret.setErrorMessage(StringUtil.filterIllegalchar(e.getMessage()));
		}
		return ret;
	}
	
	public static ReturnObject removeRuleMeeting(HttpServletRequest request, String itemId){
		ReturnObject ret = new ReturnObject();
		try {
			request.setCharacterEncoding("UTF-8");
			if(itemId == null || "".equals(itemId)){
				itemId = request.getParameter("itemId");
			}
			RuleMeetingDAO dao = new RuleMeetingDAO();
			RuleMeeting pic = dao.find(RuleMeeting.class, Integer.parseInt(itemId));
			String picName = pic.getFileDir();
			String path = request.getRealPath(Consts.FILE_UPLOAD_SAVE_DIR);
			dao.remove(RuleMeeting.class, Integer.parseInt(itemId));
			File file = new File(path + "/" + picName);
			file.delete();
		} catch (Exception e) {
			ret.SetErrored(true);
			ret.setErrorMessage(e.getMessage());
		}
		return ret;
	}
	
	public static ReturnObject operateRuleMeeting(
			HttpServletRequest httpRequest, PageContext pageContext) {
		ReturnObject retObj = null;
		try {
			httpRequest.setCharacterEncoding("UTF-8");
			User user = (User)httpRequest.getSession().getAttribute(com.infomanage.util.Consts.LOGINED_USER);
			String actionType = httpRequest.getParameter("actionType");
			if (actionType == null) {
				FileUpload fileUpload = new FileUpload("doc,docx,xls");
				SmartUpload smartUpload = fileUpload.upload(httpRequest,
						pageContext);
				SmartRequest request = smartUpload.getRequest();
				actionType = request.getParameter("actionType");
				if ("add".equals(actionType)) {
					retObj = saveRuleMeeting(smartUpload, user);
				}
				if ("modify".equals(actionType)) {
					retObj = modifyRuleMeeting(smartUpload, user);
				}
			}else if("del".equals(actionType)){
				removeRuleMeeting(httpRequest, null);
			}
		} catch (Exception e) {
			e.printStackTrace();
			retObj.setErrorMessage(e.getMessage());
		}
		return retObj;
	}
	
	private static SearchBean buildSearchCondition(HttpServletRequest request, HttpServletResponse response,
			JspWriter out) throws Exception {
		request.setCharacterEncoding("UTF-8");
		String name = request.getParameter("name");
		SearchBean searchBean = new SearchBean();
		if (!StringUtil.isEmpty(name)) {
			FieldBean field = new FieldBean("name", name);
			field.setLike(true);
			searchBean.add(field);
		}
		
		// 设置权限
		User user = (User) request.getSession().getAttribute(Consts.LOGINED_USER);
		if (user != null) {
			AuthorityBean authority = new AuthorityBean();
			authority.setRole(RoleType.valueOf(user.getRoleId()));
			authority.setDeptId(user.getAssociatedDept());
			searchBean.setAuthority(authority);
		}
		return searchBean;
	}
	
	public static int getPageCount(HttpServletRequest request, HttpServletResponse response, JspWriter out){
		try {
			RuleMeetingDAO dao = new RuleMeetingDAO();
			SearchBean searchBean = buildSearchCondition(request, response, out);
			return (dao.count(searchBean) + PaginationBean.pageSize - 1)/PaginationBean.pageSize;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 1;
	}
	
	public static List<RuleMeeting> search(HttpServletRequest request, HttpServletResponse response, JspWriter out) {
		try {
			request.setCharacterEncoding("UTF-8");
			RuleMeetingDAO dao = new RuleMeetingDAO();
			SearchBean searchBean = buildSearchCondition(request, response, out);
			//设置分页
			String currPageNum = request.getParameter("currPageNum");
			PaginationBean page = new PaginationBean();
			if(currPageNum == null){
				page.setCurrentPageNum(1);
			}else{
				page.setCurrentPageNum(Integer.parseInt(currPageNum));
				
			}
			searchBean.setPage(page);
			List<RuleMeeting> list = dao.findByFields(searchBean);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static ReturnObject removeBatchRuleMeeting(HttpServletRequest request, HttpServletResponse response, JspWriter out){
		ReturnObject ret = new ReturnObject();
		try {
			request.setCharacterEncoding("UTF-8");
			String batchIds = request.getParameter("batchIds");
			RuleMeetingDAO dao = new RuleMeetingDAO();
			if(batchIds != null){
				String[] ids = batchIds.split(";");
				for(String id : ids){
					dao.remove(RuleMeeting.class, Integer.parseInt(id));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			ret.SetErrored(true);
			ret.setErrorMessage("删除失败！");
		}
		return ret;
	}
}
